package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ContentAdapter;
import flc.ast.bean.MyMovieListBean;
import flc.ast.databinding.ActivityMovieListBinding;
import flc.ast.dialog.EditDialog;
import flc.ast.utils.AppSpUtils;
import stark.common.api.StkResApi;
import stark.common.base.IReqRetCallback;
import stark.common.basic.base.BaseWebviewActivity;
import stark.common.basic.event.EventStatProxy;
import stark.common.bean.StkResBean;
import stark.common.bean.StkResSetBean;

public class MovieListActivity extends BaseAc<ActivityMovieListBinding> {

    public static String movieListId = "";
    private List<StkResBean> listShow = new ArrayList<>();
    private MyMovieListBean currentBean;
    private ContentAdapter movieAdapter, contentAdapter;
    private Dialog myAddContentDialog, myDeleteDialog, myRenameDialog;
    private EditText dialogAdd, dialogRename;
    private RecyclerView rvContent;
    private TextView dialogTip;
    private String key;
    private boolean isSearch, isEdit;
    private BasePopupView editPopup;

    @Override
    protected int onCreate() {
        return R.layout.activity_movie_list;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivMovieListBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivMovieListEdit.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);

        mDataBinding.rvMovieList.setLayoutManager(new LinearLayoutManager(mContext));
        movieAdapter = new ContentAdapter();
        mDataBinding.rvMovieList.setAdapter(movieAdapter);
        movieAdapter.addChildClickViewIds(R.id.ivContentItemDelete);
        movieAdapter.setOnItemClickListener(this);
        movieAdapter.setOnItemChildClickListener(this);
        movieAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                isEdit = !isEdit;
                movieAdapter.setEdit(isEdit);
                movieAdapter.notifyDataSetChanged();
                return false;
            }
        });

        //删除弹框
        deleteDialog();
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivMovieListEdit://编辑
                showEditDialog();
                break;
            case R.id.ivAdd://添加
                myAddContentDialog.show();
                break;
            //添加影视内容到片单弹框
            case R.id.ivDialogAddContentSearch://搜索
                key = dialogAdd.getText().toString().trim();
                if (key.isEmpty()) {
                    ToastUtils.showShort(getString(R.string.please_input_movie_name));
                    return;
                }
                isSearch = true;
                getSearchData();
                break;
            //删除弹框
            case R.id.tvDialogDeleteConfirm://确定
                myDeleteDialog.dismiss();
                delete();
                break;
            case R.id.tvDialogDeleteCancel://取消
                myDeleteDialog.dismiss();
                break;
            //重命名弹框
            case R.id.tvDialogRenameConfirm://确定
                myRenameDialog.dismiss();
                rename();
                break;
            case R.id.tvDialogRenameCancel://取消
                myRenameDialog.dismiss();
                break;

        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        StkResBean bean = (StkResBean) adapter.getItem(position);
        BaseWebviewActivity.open(mContext, bean.getUrl(), bean.getName());
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        List<MyMovieListBean> listSp = AppSpUtils.getMovieList();
        List<StkResBean> listData = new ArrayList<>();
        for (MyMovieListBean bean : listSp) {
            if (bean.getId().equals(movieListId)) {
                listData = bean.getListData();
            }
        }
        switch (view.getId()) {
            case R.id.ivContentItemDelete://删除
                for (StkResBean listDatum : listData) {
                    if (listDatum.getUrl().equals(movieAdapter.getItem(position).getUrl())) {
                        listData.remove(listDatum);
                        break;
                    }
                }
                AppSpUtils.saveMovieList(listSp);
                getData();
                break;
            case R.id.ivContentItemZhui://追剧
                if (contentAdapter.getItem(position).isSelected()) {
                    for (StkResBean listDatum : listData) {
                        if (listDatum.getUrl().equals(contentAdapter.getItem(position).getUrl())) {
                            listData.remove(listDatum);
                            break;
                        }
                    }
                } else {
                    listData.add(0, contentAdapter.getItem(position));
                }
                AppSpUtils.saveMovieList(listSp);
                getData();
                contentAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
        //添加影视内容到片单弹框
        addContentDialog();
        getRecommendData();
    }

    private void getData() {
        listShow.clear();
        List<MyMovieListBean> listSp = AppSpUtils.getMovieList();
        if (listSp != null && listSp.size() > 0) {
            for (MyMovieListBean bean : listSp) {
                if (bean.getId().equals(movieListId)) {
                    currentBean = bean;
                    mDataBinding.tvMovieListName.setText(bean.getName());
                    long date = TimeUtils.string2Millis(bean.getId(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                    mDataBinding.tvMovieListDate.setText(getString(R.string.add_time_num, TimeUtils.millis2String(date, new SimpleDateFormat("yyyy/MM/dd"))));
                    mDataBinding.tvMovieListSize.setText(getString(R.string.movie_list_content_num, bean.getListData().size()));
                    listShow.addAll(bean.getListData());
                    if (listShow != null && listShow.size() != 0) {
                        Glide.with(mContext).load(listShow.get(0).getThumbUrl()).into(mDataBinding.ivMovieListImg);
                        mDataBinding.rlMovieListImg.setVisibility(View.VISIBLE);
                    } else {
                        mDataBinding.rlMovieListImg.setVisibility(View.GONE);
                    }
                    break;
                }
            }
        }
        if (listShow.size() > 0) {
            movieAdapter.setList(listShow);
            mDataBinding.rvMovieList.setVisibility(View.VISIBLE);
            mDataBinding.tvMovieListNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvMovieList.setVisibility(View.GONE);
            mDataBinding.tvMovieListNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getRecommendData() {
        StkResApi.getTagResourceList(this, AppConfig.RECOMMEND_DATA, StkResApi.createParamMap(0, 10), false, new IReqRetCallback<List<StkResBean>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<StkResBean> result) {
                if (success) {
                    if (result != null && result.size() > 0) {
                        contentAdapter.setListSp(listShow);
                        contentAdapter.setList(result);
                    }
                }
            }
        });
    }

    private void getSearchData() {
        dialogTip.setText(getString(R.string.search_result));
        StkResApi.getTagResourceList(this, AppConfig.SEARCH_DATA + key, StkResApi.createParamMap(0, 99), false, new IReqRetCallback<List<StkResBean>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<StkResBean> result) {
                if (success) {
                    if (result != null && result.size() > 0) {
                        contentAdapter.setListSp(listShow);
                        contentAdapter.setList(result);
                        rvContent.setVisibility(View.VISIBLE);
                    } else {
                        rvContent.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    //删除片单
    private void delete() {
        List<MyMovieListBean> listSp = AppSpUtils.getMovieList();
        if (listSp != null && listSp.size() > 0) {
            for (int i = 0; i < listSp.size(); i++) {
                if (listSp.get(i).getId().equals(movieListId)) {
                    listSp.remove(i);
                    break;
                }
            }
            AppSpUtils.saveMovieList(listSp);
            ToastUtils.showShort(getString(R.string.delete_suc));
            finish();
        }
    }

    //重命名
    private void rename() {
        String albumName = dialogRename.getText().toString();
        if (TextUtils.isEmpty(albumName)) {
            ToastUtils.showShort(R.string.please_input_movie_list_name);
            return;
        }
        myRenameDialog.dismiss();
        List<MyMovieListBean> listSp = AppSpUtils.getMovieList();
        if (listSp != null && listSp.size() > 0) {
            for (int i = 0; i < listSp.size(); i++) {
                if (listSp.get(i).getId().equals(movieListId)) {
                    listSp.get(i).setName(albumName);
                    break;
                }
            }
            AppSpUtils.saveMovieList(listSp);
        }
        getData();
    }

    //添加影视内容到片单弹框
    private void addContentDialog() {
        myAddContentDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_content, null);
        myAddContentDialog.setContentView(inflate);
        myAddContentDialog.setCancelable(true);
        Window dialogWindow = myAddContentDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        ImageView ivSearch = inflate.findViewById(R.id.ivDialogAddContentSearch);

        rvContent = inflate.findViewById(R.id.rvContentList);
        rvContent.setLayoutManager(new LinearLayoutManager(mContext));
        contentAdapter = new ContentAdapter();
        contentAdapter.setShowZhui(true);
        rvContent.setAdapter(contentAdapter);
        contentAdapter.addChildClickViewIds(R.id.ivContentItemZhui);
        contentAdapter.setOnItemChildClickListener(this);

        dialogTip = inflate.findViewById(R.id.tvDialogAddContentTip);
        dialogAdd = inflate.findViewById(R.id.etDialogAddContentText);
        ivSearch.setOnClickListener(this);
    }

    private void showEditDialog() {
        EditDialog editDialog = new EditDialog(mContext);
        editPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivMovieListEdit).hasShadowBg(true) // 去掉半透明背景
                .asCustom(editDialog);
        editPopup.show();
        editDialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickDelete() {
                editPopup.dismiss();
                myDeleteDialog.show();
            }

            @Override
            public void clickEdit() {
                editPopup.dismiss();
                dialogRename.setText(currentBean.getName());
                myRenameDialog.show();
            }
        });
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogDeleteConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteCancel);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogRenameConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        dialogRename = inflate.findViewById(R.id.etDialogRenameText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

}